package com.chagee.store.operation.server.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chagee.store.operation.api.enums.OrderAppealTypeEnum;
import com.chagee.store.operation.api.enums.StoreWorkOrderStatusEnum;
import com.chagee.store.operation.common.constant.CommonConstant;
import com.chagee.store.operation.server.entity.*;
import com.chagee.store.operation.server.event.dao.WorkOrderMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.chagee.store.operation.server.event.service.*;
import com.google.common.collect.Sets;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 刷新工单评分数据
 * @Author : hk
 * @Date : 2025/2/06
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class RefreshOrderAppealHandler {

	@Resource
	private WorkOrderMapper workOrderMapper;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;

	@Resource
	private WorkOrderReceiverBaseService workOrderReceiverBaseService;

	/**
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("refreshOrderAppealHandler")
	public ReturnT<String> refreshOrderScoreHandler(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("刷新工单申诉定时任务开始,traceId :{}", span.getTraceId());
		try {

			if (StringUtils.isNotBlank(param)) {
				List<String> storeCodeList = Arrays.stream(param.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
				queryWrapper.in(WorkOrderDO::getStoreCode, storeCodeList);
				List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(queryWrapper);

				log.info("workOrderDOList,traceId :{}", JSONUtil.toJsonStr(workOrderDOList));
				Set<Integer> orderStatusList = Sets.newHashSet(StoreWorkOrderStatusEnum.IN_APPEAL.getType(), StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType());
				for (WorkOrderDO workOrderDO : workOrderDOList) {
					try {
						LambdaQueryWrapper<TaskExecutionDO> wrapper = new LambdaQueryWrapper<>();
						wrapper.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
						wrapper.eq(TaskExecutionDO::getWorkOrderNumber, workOrderDO.getWorkOrderNumber());
						List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(wrapper);
						//申诉过
						List<TaskExecutionDO> collect = taskExecutionDOS.stream().filter(s -> ObjectUtils.isNotEmpty(s.getAppealStatus())).collect(Collectors.toList());
						OrderAppealTypeEnum appealType = OrderAppealTypeEnum.NO_APPEAL;
						if (CollectionUtils.isNotEmpty(collect) || StringUtils.isNotBlank(workOrderDO.getAppealResult()) || orderStatusList.contains(workOrderDO.getDocumentStatus())) {
							appealType = OrderAppealTypeEnum.APPEAL;
						}
						workOrderDO.setAppealFlag(appealType.name());
					} catch (Exception e) {
						log.error("刷新工单申诉定时任务异常:工单号 : {}, storeId:{}, startIndex:{} 异常信息 : ", workOrderDO.getWorkOrderNumber(), workOrderDO.getStoreCode(), e);
					}
				}
				updateAppealFlag(workOrderDOList);

			}else {
				int startIndex = 0;
				while (true) {
					log.info("start_index " + startIndex);
					LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
					queryWrapper.eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
					queryWrapper.gt(WorkOrderDO::getId, startIndex);
					queryWrapper.orderByAsc(WorkOrderDO::getId);
					queryWrapper.last(CommonConstant.LIMIT_SIZE_SQL);
					List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(queryWrapper);

					if (CollectionUtils.isEmpty(workOrderDOList)) {
						break;
					}

					for (WorkOrderDO workOrderDO : workOrderDOList) {
						try {
							LambdaQueryWrapper<TaskExecutionDO> wrapper = new LambdaQueryWrapper<>();
							wrapper.eq(TaskExecutionDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
							wrapper.eq(TaskExecutionDO::getWorkOrderNumber, workOrderDO.getWorkOrderNumber());
							List<TaskExecutionDO> taskExecutionDOS = taskExecutionBaseService.list(wrapper);
							//申诉过
							List<TaskExecutionDO> collect = taskExecutionDOS.stream().filter(s -> ObjectUtils.isNotEmpty(s.getAppealStatus())).collect(Collectors.toList());
							OrderAppealTypeEnum appealType = OrderAppealTypeEnum.NO_APPEAL;
							if (CollectionUtils.isNotEmpty(collect) || StringUtils.isNotBlank(workOrderDO.getAppealResult())) {
								appealType = OrderAppealTypeEnum.APPEAL;
							}
							workOrderDO.setAppealFlag(appealType.name());
						} catch (Exception e) {
							log.error("刷新工单申诉定时任务异常:工单号 : {}, storeId:{}, startIndex:{} 异常信息 : ", workOrderDO.getWorkOrderNumber(), workOrderDO.getStoreCode(), startIndex, e);
						}
					}
					updateAppealFlag(workOrderDOList);
					startIndex = Math.toIntExact(workOrderDOList.stream().map(WorkOrderDO::getId).max(Comparator.naturalOrder()).orElse(0L));

				}
			}
		} catch (Exception e) {
			XxlJobLogger.log("刷新工单评分定时任务异常，异常信息:", e);
			log.error("刷新工单申诉定时任务异常 => param : {} => 异常信息: ", param, e);
		}
		XxlJobLogger.log("刷新工单申诉定时任务结束，traceId :{},共耗时:{}", span.getTraceId(), timer.intervalRestart());
		return ReturnT.SUCCESS;
	}

	public void updateAppealFlag(List<WorkOrderDO> workOrderDOS) {
		workOrderDOS.forEach(s -> {
			LambdaUpdateWrapper<WorkOrderDO> wrapper = new LambdaUpdateWrapper<>();
			wrapper.eq(WorkOrderDO::getWorkOrderNumber, s.getWorkOrderNumber());
			wrapper.set(WorkOrderDO::getAppealFlag, s.getAppealFlag());
			workOrderMapper.update(wrapper);
		});
	}


	/**
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("refreshOrderAppealHandler1")
	public ReturnT<String> refreshOrderScoreHandler1(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("刷新工单申诉定时任务开始11,traceId :{}", span.getTraceId());
		try {
			LambdaQueryWrapper<WorkOrderDO> queryWrapper = new LambdaQueryWrapper<>();
			queryWrapper.eq(WorkOrderDO::getDocumentStatus, StoreWorkOrderStatusEnum.EXPIRED_APPEAL.getType());
			List<WorkOrderDO> workOrderDOList = workOrderMapper.selectList(queryWrapper);

			if (CollectionUtil.isNotEmpty(workOrderDOList)) {
				workOrderDOList.forEach(s -> {
					LambdaUpdateWrapper<WorkOrderDO> wrapper = new LambdaUpdateWrapper<>();
					wrapper.eq(WorkOrderDO::getWorkOrderNumber, s.getWorkOrderNumber());
					wrapper.set(WorkOrderDO::getAppealFlag, OrderAppealTypeEnum.APPEAL.name());
					workOrderMapper.update(wrapper);
				});
			}

		} catch (Exception e) {
			XxlJobLogger.log("刷新工单评分定时任务异常，异常信息:", e);
			log.error("刷新工单申诉定时任务异常 => param : {} => 异常信息: ", param, e);
		}
		XxlJobLogger.log("刷新工单申诉定时任务结束，traceId :{},共耗时:{}", span.getTraceId(), timer.intervalRestart());
		return ReturnT.SUCCESS;
	}


}
